using System;
using System.Data;
using System.Data.SqlClient;

namespace Tyng.Data.Utilities
{
	public sealed class Database : IDisposable
	{
		private const int DefaultTimeout = 120;

        string _runtime;
		string _name;
		string _connectionString;
		string _path;
		string _rawPath;
		SqlConnection _conn;

		public Database(string runtime, string name, string connectionString, string path, string rawPath)
		{
            _runtime = runtime;
            _name = name;
			_connectionString = connectionString;
			_path = path;
			_rawPath = rawPath;
		}

        public string RunTimeName { get { return _runtime; } }
        public string Name { get { return _name; } }
		public string Path { get { return _path; } }
		public string RawPath { get { return _rawPath; } }
		public string ConnectionString { get { return _connectionString; } }
	
		private SqlConnection Connection
		{
			get
			{
				if(_conn == null)
				{
					_conn = new SqlConnection(_connectionString);
					_conn.Open();
				}

				return _conn;
			}
		}

		public IDataReader ExecuteReader(string sql)
		{
			return ExecuteReader(sql, CommandBehavior.Default);
		}

		public IDataReader ExecuteReader(string sql, CommandBehavior behavior)
		{
			return GetCommand(sql).ExecuteReader(behavior);
		}

		public object ExecuteScalar(string sql)
		{
			return GetCommand(sql).ExecuteScalar();
		}

		public void ExecuteNonQuery(string sql)
		{
			GetCommand(sql).ExecuteNonQuery();
		}

		private SqlCommand GetCommand(string sql)
		{
			int timeout = DefaultTimeout;
            string timeoutString = HybridSettings.GetValue("CommandTimeout");

			if(timeoutString != null && timeoutString.Length > 0)
				timeout = int.Parse(timeoutString);

			SqlCommand cmd = new SqlCommand(sql, Connection);
			
			cmd.CommandTimeout = timeout;

			return cmd;
		}

		#region IDisposable Members

		public void Dispose()
		{
			if(_conn != null)
				_conn.Dispose();				
		}

		#endregion
	}

	
}
